package com.oitsm.sys.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.oitsm.commons.action.BaseAction;
import com.oitsm.sys.cache.MenuCache;
import com.oitsm.sys.entity.Menu;
import com.oitsm.utils.JSONUtils;
/**
 * 菜单Action
 * @author Arab Runner
 * Jun 18, 2011 3:58:48 PM
 */
@SuppressWarnings("serial")
public class MenuAction extends BaseAction {
	/**
	 * 获取菜单
	 * @return
	 * @throws Exception
	 */
	public String getMenus()throws Exception{
		HttpServletRequest request = this.getRequest();
		String webContext = request.getContextPath();
		Long parentId = 0l;
		try{
			parentId = new Long(request.getParameter("node"));
		}catch(Exception e){
		}
		List<Menu> menus = MenuCache.getMenusByParentId(parentId);
		JSONArray ja = new JSONArray();
		encodeMenuJson(menus,ja,webContext);
		JSONUtils.write(this.getResponse(), ja.toString());
		return null;
	}
	
	private void encodeMenuJson(List<Menu> menus,JSONArray ja,String webContext){
		for(Menu menu : menus){
			JSONObject jo = new JSONObject();
			jo.put("id", menu.getId());
			if(StringUtils.isNotEmpty(menu.getIcon())){
				jo.put("icon", webContext + menu.getIcon());
			}
			jo.put("jsPaths", menu.getJsPaths());
			String className = menu.getComponentName();
			String param = "";
			int splitIndex = className.indexOf("?");
			if(splitIndex>0){
				className = menu.getComponentName().substring(0,splitIndex);
				param = menu.getComponentName().substring(splitIndex+1);
			}
			jo.put("className", className);
			jo.put("param", encodeParam(param));
			jo.put("text", menu.getName());
			if(menu.getType() == 0){
				jo.put("leaf", true);
				jo.put("isLeafNode", true);
			}
			
			if(menu.getChildren()!= null && menu.getChildren().size()>0){
				JSONArray childJa = new JSONArray();
				encodeMenuJson(menu.getChildren(),childJa,webContext);
				jo.put("children", childJa);
			}else{
				jo.put("leaf", true);
			}
			
			ja.add(jo);
		}
	}
	
	private static JSONObject encodeParam(String paramStr){
		JSONObject jo = new JSONObject();
		String[] params = paramStr.split("&");
		for(String param : params){
			String[] pair = param.split("=");
			if(pair.length!=2){
				continue;
			}
			jo.put(pair[0], pair[1]);
		}
		return jo;
	}
}
